#include "TcpServer.hpp"
#include <memory>

void business(QiHai::Request& req, QiHai::Response& res)
{
    res._state = 1;
    switch (req._op)
    {
    case '+':
        res._result = req._x + req._y;
        break;
    case '-':
        res._result = req._x - req._y;
        break;
    case '*':
        res._result = req._x * req._y;
        break;
    case '/':
        if (req._y == 0)
        {
            res._state = 0;
            res._result = 1;  // 除0异常
        }
        else res._result = req._x / req._y;
        break;
    case '%':
        if (req._y == 0)
        {
            res._state = 0;
            res._result = 2;  // 模0异常
        }
        else res._result = req._x % req._y;
        break;
    default:
        res._state = 0;
        res._result = 3;  // 未知运算符
        break;
    }
}

void Natcb(QiHai::Connection* conn, std::string message)
{
    // 上层业务处理
    // 接收到一个报文后，因为是一个结构化的东西，首先进行反序列化
    QiHai::Request req;
    if (!req.deserialization(message))
    {
        logMessage(WARNING, "Request deserialization error!");
        return;
    }

    QiHai::Response res;
    business(req, res);
    conn->_outbuffer += res.serialization();
    conn->_tsvr->EnableReadWrite(conn, true, true);  // 修改一次写的状态，剩下由服务器进行处理
}

int main()
{
    std::unique_ptr<QiHai::TcpServer> server(new QiHai::TcpServer);
    server->Dispather(Natcb);

    // QiHai::Response res;
    // res.deserialization("{\"state\":1,\"result\":2}");
    // std::cout << res.serialization() << std::endl;

    // QiHai::Request req;
    // std::string msg = "{\"op\":43,\"x\":1,\"y\":2}";
    // req.deserialization(msg);
    // std::cout << req.serialization() << std::endl;

    // QiHai::Request req(1, 2, '+');
    // std::cout << req.serialization() << std::endl;
    return 0;
}